// pages/anxiety/breathing.js
const app = getApp();
const themeManager = require('../../utils/theme-manager');
const storage = require('../../utils/storage');

Page({
  data: {
    // 主题相关
    currentTheme: 'pink',
    themeColors: {},
    
    // 呼吸练习状态
    isActive: false,
    isPaused: false,
    currentPhase: 'inhale', // inhale, hold, exhale, rest
    phaseTime: 0,
    totalTime: 0,
    sessionDuration: 300, // 5分钟默认
    
    // 呼吸模式
    breathingPatterns: [
      {
        id: 'basic',
        name: '基础呼吸',
        description: '4-4-4-4 节奏，适合初学者',
        inhale: 4,
        holdIn: 4,
        exhale: 4,
        holdOut: 4,
        color: '#87CEEB'
      },
      {
        id: 'calm',
        name: '平静呼吸',
        description: '4-7-8 节奏，快速放松',
        inhale: 4,
        holdIn: 7,
        exhale: 8,
        holdOut: 0,
        color: '#DDA0DD'
      },
      {
        id: 'energy',
        name: '活力呼吸',
        description: '6-2-6-2 节奏，提升专注',
        inhale: 6,
        holdIn: 2,
        exhale: 6,
        holdOut: 2,
        color: '#98FB98'
      },
      {
        id: 'deep',
        name: '深度呼吸',
        description: '8-4-8-4 节奏，深度放松',
        inhale: 8,
        holdIn: 4,
        exhale: 8,
        holdOut: 4,
        color: '#F0E68C'
      }
    ],
    selectedPattern: null,
    
    // 时长选项
    durationOptions: [
      { value: 180, label: '3分钟' },
      { value: 300, label: '5分钟' },
      { value: 600, label: '10分钟' },
      { value: 900, label: '15分钟' }
    ],
    
    // 引导文本
    phaseTexts: {
      inhale: '慢慢吸气...',
      holdIn: '屏住呼吸...',
      exhale: '缓缓呼气...',
      holdOut: '自然停顿...'
    },
    
    // 动画状态
    circleScale: 1,
    circleOpacity: 0.8,
    
    // 统计数据
    sessionStats: {
      completedCycles: 0,
      totalBreaths: 0,
      averageHeartRate: 0
    },
    
    // UI状态
    showPatternSelector: false,
    showSettings: false,
    showStats: false,
    
    // 音效设置
    soundEnabled: true,
    vibrationEnabled: true,
    
    // 定时器
    timer: null,
    animationTimer: null
  },

  onLoad(options) {
    this.initTheme();
    this.loadSettings();
    this.setDefaultPattern();
  },

  onUnload() {
    this.stopBreathing();
  },

  // 初始化主题
  initTheme() {
    const userInfo = app.globalData.userInfo || {};
    const theme = userInfo.role === 'male' ? 'gold' : 'pink';
    const colors = themeManager.getThemeColors(theme);
    
    this.setData({
      currentTheme: theme,
      themeColors: colors
    });
  },

  // 加载设置
  loadSettings() {
    const settings = storage.get('breathingSettings') || {
      soundEnabled: true,
      vibrationEnabled: true,
      defaultDuration: 300
    };
    
    this.setData({
      soundEnabled: settings.soundEnabled,
      vibrationEnabled: settings.vibrationEnabled,
      sessionDuration: settings.defaultDuration
    });
  },

  // 设置默认模式
  setDefaultPattern() {
    const defaultPattern = this.data.breathingPatterns[0];
    this.setData({ selectedPattern: defaultPattern });
  },

  // 选择呼吸模式
  onSelectPattern(e) {
    const pattern = e.currentTarget.dataset.pattern;
    this.setData({
      selectedPattern: pattern,
      showPatternSelector: false
    });
  },

  // 选择时长
  onSelectDuration(e) {
    const duration = parseInt(e.currentTarget.dataset.duration);
    this.setData({ sessionDuration: duration });
  },

  // 开始呼吸练习
  onStartBreathing() {
    if (!this.data.selectedPattern) {
      wx.showToast({
        title: '请选择呼吸模式',
        icon: 'none'
      });
      return;
    }

    this.setData({
      isActive: true,
      isPaused: false,
      currentPhase: 'inhale',
      phaseTime: 0,
      totalTime: 0,
      sessionStats: {
        completedCycles: 0,
        totalBreaths: 0,
        averageHeartRate: 0
      }
    });

    this.startBreathingCycle();
    this.startAnimation();
  },

  // 暂停/恢复
  onTogglePause() {
    const isPaused = !this.data.isPaused;
    this.setData({ isPaused });

    if (isPaused) {
      this.pauseBreathing();
    } else {
      this.resumeBreathing();
    }
  },

  // 停止练习
  onStopBreathing() {
    this.stopBreathing();
    this.saveSession();
    this.showSessionSummary();
  },

  // 开始呼吸周期
  startBreathingCycle() {
    const { selectedPattern } = this.data;
    this.executePhase('inhale', selectedPattern.inhale);
  },

  // 执行呼吸阶段
  executePhase(phase, duration) {
    if (!this.data.isActive || this.data.isPaused) return;

    this.setData({
      currentPhase: phase,
      phaseTime: 0
    });

    this.data.timer = setInterval(() => {
      if (this.data.isPaused) return;

      const phaseTime = this.data.phaseTime + 1;
      const totalTime = this.data.totalTime + 1;

      this.setData({
        phaseTime,
        totalTime
      });

      // 阶段完成
      if (phaseTime >= duration) {
        clearInterval(this.data.timer);
        this.nextPhase();
      }

      // 会话结束
      if (totalTime >= this.data.sessionDuration) {
        this.onStopBreathing();
      }
    }, 1000);

    // 播放提示音
    if (this.data.soundEnabled) {
      this.playPhaseSound(phase);
    }

    // 震动提示
    if (this.data.vibrationEnabled) {
      wx.vibrateShort();
    }
  },

  // 下一个阶段
  nextPhase() {
    const { currentPhase, selectedPattern } = this.data;
    let nextPhase, duration;

    switch (currentPhase) {
      case 'inhale':
        nextPhase = 'holdIn';
        duration = selectedPattern.holdIn;
        break;
      case 'holdIn':
        nextPhase = 'exhale';
        duration = selectedPattern.exhale;
        break;
      case 'exhale':
        nextPhase = 'holdOut';
        duration = selectedPattern.holdOut;
        break;
      case 'holdOut':
        nextPhase = 'inhale';
        duration = selectedPattern.inhale;
        // 完成一个完整周期
        this.updateStats();
        break;
    }

    if (duration > 0) {
      this.executePhase(nextPhase, duration);
    } else {
      // 跳过时长为0的阶段
      this.setData({ currentPhase: nextPhase });
      this.nextPhase();
    }
  },

  // 更新统计
  updateStats() {
    const stats = { ...this.data.sessionStats };
    stats.completedCycles++;
    stats.totalBreaths += 2; // 一次吸气+呼气
    
    this.setData({ sessionStats: stats });
  },

  // 暂停呼吸
  pauseBreathing() {
    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
    if (this.data.animationTimer) {
      clearInterval(this.data.animationTimer);
    }
  },

  // 恢复呼吸
  resumeBreathing() {
    const { currentPhase, phaseTime, selectedPattern } = this.data;
    const remainingTime = this.getPhaseMaxTime(currentPhase) - phaseTime;
    
    if (remainingTime > 0) {
      this.executePhase(currentPhase, remainingTime);
    } else {
      this.nextPhase();
    }
    
    this.startAnimation();
  },

  // 停止呼吸
  stopBreathing() {
    this.setData({
      isActive: false,
      isPaused: false,
      currentPhase: 'inhale',
      phaseTime: 0
    });

    if (this.data.timer) {
      clearInterval(this.data.timer);
    }
    if (this.data.animationTimer) {
      clearInterval(this.data.animationTimer);
    }
  },

  // 开始动画
  startAnimation() {
    this.data.animationTimer = setInterval(() => {
      if (this.data.isPaused) return;
      
      this.updateCircleAnimation();
    }, 100);
  },

  // 更新圆圈动画
  updateCircleAnimation() {
    const { currentPhase, phaseTime, selectedPattern } = this.data;
    const maxTime = this.getPhaseMaxTime(currentPhase);
    const progress = phaseTime / maxTime;

    let scale, opacity;
    
    switch (currentPhase) {
      case 'inhale':
        scale = 1 + progress * 0.5; // 1 -> 1.5
        opacity = 0.6 + progress * 0.4; // 0.6 -> 1
        break;
      case 'holdIn':
        scale = 1.5;
        opacity = 1;
        break;
      case 'exhale':
        scale = 1.5 - progress * 0.5; // 1.5 -> 1
        opacity = 1 - progress * 0.4; // 1 -> 0.6
        break;
      case 'holdOut':
        scale = 1;
        opacity = 0.6;
        break;
    }

    this.setData({
      circleScale: scale,
      circleOpacity: opacity
    });
  },

  // 获取阶段最大时间
  getPhaseMaxTime(phase) {
    const { selectedPattern } = this.data;
    switch (phase) {
      case 'inhale': return selectedPattern.inhale;
      case 'holdIn': return selectedPattern.holdIn;
      case 'exhale': return selectedPattern.exhale;
      case 'holdOut': return selectedPattern.holdOut;
      default: return 0;
    }
  },

  // 播放阶段提示音
  playPhaseSound(phase) {
    // 这里可以添加音效播放逻辑
    // wx.createInnerAudioContext() 播放不同阶段的提示音
  },

  // 保存会话
  saveSession() {
    const sessionData = {
      pattern: this.data.selectedPattern.name,
      duration: this.data.totalTime,
      stats: this.data.sessionStats,
      timestamp: Date.now()
    };

    const sessions = storage.get('breathingSessions') || [];
    sessions.unshift(sessionData);
    
    // 只保留最近50次记录
    if (sessions.length > 50) {
      sessions.splice(50);
    }
    
    storage.set('breathingSessions', sessions);
  },

  // 显示会话总结
  showSessionSummary() {
    const { totalTime, sessionStats } = this.data;
    const minutes = Math.floor(totalTime / 60);
    const seconds = totalTime % 60;
    
    wx.showModal({
      title: '练习完成',
      content: `练习时长：${minutes}分${seconds}秒\n完成周期：${sessionStats.completedCycles}次\n总呼吸次数：${sessionStats.totalBreaths}次`,
      showCancel: false,
      confirmText: '好的'
    });
  },

  // 显示模式选择器
  onShowPatternSelector() {
    this.setData({ showPatternSelector: true });
  },

  // 显示设置
  onShowSettings() {
    this.setData({ showSettings: true });
  },

  // 显示统计
  onShowStats() {
    this.setData({ showStats: true });
  },

  // 切换音效
  onToggleSound() {
    const soundEnabled = !this.data.soundEnabled;
    this.setData({ soundEnabled });
    this.saveSettings();
  },

  // 切换震动
  onToggleVibration() {
    const vibrationEnabled = !this.data.vibrationEnabled;
    this.setData({ vibrationEnabled });
    this.saveSettings();
  },

  // 保存设置
  saveSettings() {
    const settings = {
      soundEnabled: this.data.soundEnabled,
      vibrationEnabled: this.data.vibrationEnabled,
      defaultDuration: this.data.sessionDuration
    };
    
    storage.set('breathingSettings', settings);
  },

  // 关闭弹窗
  onCloseModal() {
    this.setData({
      showPatternSelector: false,
      showSettings: false,
      showStats: false
    });
  },

  // 格式化时间
  formatTime(seconds) {
    const mins = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
  },

  // 获取进度百分比
  getProgress() {
    return Math.round((this.data.totalTime / this.data.sessionDuration) * 100);
  },

  onShareAppMessage() {
    return {
      title: '呼吸引导 - 找到内心的平静',
      path: '/pages/anxiety/breathing',
      imageUrl: '/images/breathing-share.png'
    };
  }
});